import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';

import '../../data/models/bt_oss_policy.dart';

Future<String> fileUpload(XFile? file, BtOssPolicy policy) async {
  DateTime dateTime = DateTime.now();
  String? fileName = file?.path.split('/').last;
  String? format = fileName?.split('.').last;
  int imageTimeName = dateTime.millisecondsSinceEpoch + (dateTime.microsecondsSinceEpoch ~/ 1000000);
  String imageName = '$imageTimeName.$format';
  String host = policy.host;
  String dir = policy.dir;
  var filePath = await MultipartFile.fromFile(file!.path, filename: fileName);
  final formData = FormData.fromMap({
    'ossaccessKeyId': policy.accessKeyId,
    'policy': policy.policy,
    'signature': policy.signature,
    'callback': policy.callback,
    'key': '$dir/$imageName',
    'file': filePath,
  });
  Dio dio = Dio();
  var response = await dio.post(host, data: formData);
  if (kDebugMode) {
    print("File Upload Back：$response");
  }
  if (response.data != null && response.data["data"]["filename"] != null) {
    return response.data["data"]["filename"];
  }

  return '';
}
